package Reactor;

import java.sql.*;

public class JDBC {

    private final static String jdbcurl = "jdbc:mysql://localhost:3306/test";
    private final static String user = "root";
    private final static String password = "123456";
    private final static String Driver = "com.mysql.cj.jdbc.Driver";

    private Connection connection = null;

    //连接
    public void accept() {
        try {
            Class.forName(Driver);
            connection = DriverManager.getConnection(jdbcurl,user,password);
            if (!connection.isClosed()){
                System.out.println("数据库连接成功.........");
            }
        }catch (Exception e) {
            System.out.println("数据库连接失败...........");
        }
    }
    //关闭连接
    public void close() {
        try {
            this.connection.isClosed();
            System.out.println("关闭连接成功........");
        }catch (Exception e){
            System.out.println("关闭连接失败........");
        }
    }
    //插入数据
    public void insert(int id,String name,String date,String re){
        String sql = "insert into Re(id,name,date,re) values(?,?,?,?)";

        try {
            PreparedStatement psmat = connection.prepareStatement(sql);
            psmat.setInt(1,id);
            psmat.setString(2,name);
            psmat.setString(3,date);
            psmat.setString(4,re);
            System.out.println("插入成功");
        }catch (Exception e) {
            System.out.println("插入失败");
        }
    }

    //查询
    public void select() {
        String sql = "select * from Re";
        try {
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);
            System.out.println("-----------------------------------------------------");
            System.out.println("id"+" "+"\t"+" "+"name"+" "+"\t"+" "+"date"+" "+"\t"+" "+"re");
            System.out.println("------------------------------------------------------");
            while (resultSet.next()){
                int id1 = resultSet.getInt("id");
                String name1 = resultSet.getString("name");
                String date1 = resultSet.getString("date");
                String re1 = resultSet.getString("re");
                System.out.println(id1+"\t"+name1+"\t"+date1+"\t"+re1);
                System.out.println();
            }
        }catch (Exception e){

        }
    }
}
